import Vue from 'vue';

/** 更新子属性 */
function updateChildren(oldList: any[], newList: any[]): void {
    let oLen: number = oldList ? oldList.length : 0;
    let nLen: number = newList ? newList.length : 0;
    let i: number, j: number, tmp: any, k: string;
    let flag: boolean;
    if (oLen > nLen) {
        //删除操作
        for (i = oLen - 1; i >= 0; i--) {
            flag = false;
            tmp = oldList[i];
            for (j = 0; j < nLen; j++) {
                if (tmp.id === newList[j].id) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                oldList.splice(i, 1);
            }
        }
    } else if (nLen > oLen) {
        //添加操作
        for (i = 0; i < nLen; i++) {
            flag = false;
            tmp = newList[i];
            for (j = 0; j < oLen; j++) {
                if (tmp.id === oldList[j].id) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                //todo 验证排序问题
                if (i < oLen) {
                    oldList.splice(i, 0, tmp);
                } else {
                    oldList.push(tmp);
                }
            }
        }
    }
    for (i = 0; i < nLen; i++) {
        tmp = newList[i];
        for (k in tmp) {
            oldList[i][k] = tmp[k];
        }
    }
}

/** 添加子 */
export const addTreeChildren = function (data: any, id: number | string, children: any[]): boolean {
    if (data.id === id) {
        if (data.children && data.children.length > 0) {
            Vue.set(data, 'children', children);
            updateChildren(data.children, children);
        } else {
            Vue.set(data, 'children', children);
        }
        return true;
    } else {
        let len = data.children ? data.children.length : 0;
        for (let i = 0; i < len; i++) {
            let tmp: any = data.children[i];
            if (tmp.id === id) {
                if (tmp.children && tmp.children.length > 0) {
                    updateChildren(tmp.children, children);
                } else {
                    Vue.set(tmp, 'children', children);
                }
                return true;
            } else {
                if (addTreeChildren(tmp, id, children)) {
                    return true;
                };
            }
        }
    }

    return false;
}


var tmpData: any
export const findTreeNode = function (list: any[], id: number | string): any {
    let data: any, tmp: any;
    let len = list ? list.length : 0;
    for (let i = 0; i < len; i++) {
        tmp = list[i];
        if (tmp.id == id) {
            data = tmp;
            tmpData = tmp
            return data;
        } else if (tmp.children && tmp.children.length > 0) {
            data = findTreeNode(tmp.children, id);
            // break;
        }
    }

    if (!data) {
        data = tmpData
    }
    return data;
}